import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('拦截返回键'),
        ),
        body: HomeScreen(),
      ),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        color: Colors.orange,
        child: TextButton(
          child: Text('go'),
          onPressed: () {
            Navigator.of(context)
                .push(MaterialPageRoute(builder: (ctx) => BackPageScreen()));
          },
        ),
      ),
    );
  }
}

class BackPageScreen extends StatefulWidget {
  @override
  _BackPageScreenState createState() => _BackPageScreenState();
}

class _BackPageScreenState extends State<BackPageScreen> {
  var lastPressTime; // 上次点击事件
  var isShowHint = false; // 是否显示提示文本

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('拦截返回键'),
      ),
      body: WillPopScope(
          child: Text(isShowHint ? '再次点击退出' : ''),
          onWillPop: () {
            if (lastPressTime == null ||
                DateTime.now().difference(lastPressTime) >
                    Duration(seconds: 1)) {
              lastPressTime = DateTime.now();
              setState(() {
                isShowHint = true;
              });
              // 延迟隐藏提示
              Future.delayed(
                  Duration(seconds: 1),
                  () => setState(() {
                        isShowHint = false;
                      }));
              return Future.value(false); // 不退出
            }
            return Future.value(true); // 退出
          }),
    );
  }
}
